import unittest
import ddt
import selenium.common.exceptions
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.service import Service
from ltd.hanamaki.python.unittest.paramter.ioutil.FileUtils import *

dp1 = get_file_data('data.txt')


@ddt.ddt()
class TestEcShopLogin(unittest.TestCase):
    driver = None

    @classmethod
    def setUpClass(cls) -> None:
        service = Service(executable_path='../../dirver_exe/geckodriver.exe')
        cls.driver = webdriver.Firefox(service=service)

        # 隐式等待
        cls.driver.implicitly_wait(15)

    @ddt.data(*dp1)
    def test_ecShopLogin(self, data):
        self.driver.get("http://192.168.0.109/ecshop/")
        if self.driver.page_source.__contains__('退出'):
            self.driver.find_element(By.XPATH, "/html/body/div[1]/div[2]/ul/li[1]/font/font/a[2]").click()
            self.login(data)
            self.assert_login(data)

        else:
            self.login(data)
            self.assert_login(data)

        # 通过断言 判断登录 是否成功
        self.assertEqual(True, self.driver.page_source.__contains__(data[0]), '用户名或密码错误！')

    @classmethod
    def tearDownClass(cls) -> None:
        cls.driver.quit()

    def login(self, data):
        self.driver.find_element(By.CSS_SELECTOR, "#ECS_MEMBERZONE > a:nth-child(2) > img").click()
        self.driver.find_element(By.NAME, "username").send_keys(data[0])
        self.driver.find_element(By.NAME, "password").send_keys(data[1])
        self.driver.find_element(By.NAME, "submit").click()

    def assert_login(self, data):
        try:
            info = self.driver.switch_to.alert.text
            self.driver.switch_to.alert.accept()

            self.assertEqual(data[2], info.__contains__('不能为空'), '用户名或者密码不能为空')
        except selenium.common.exceptions.NoAlertPresentException:
            print('登陆成功的，不需要操作')


if __name__ == '__main__':
    unittest.main()
